class Solution {
public:
    /**
     * @param s: the string
     * @return: length of longest semi alternating substring
     */
    int longestSemiAlternatingSubstring(string &s) {
        // write your code here
        int maxlen = 0;
        int slow = 0;
        int fast = 1;
        int size = s.size();
        int count = 1;
        
        if (size <= 2) {
            return size;
        }
        
        while (fast < size) {
            if (s[fast - 1] == s[fast]) {
                if (count == 2) {
                    maxlen = maxlen > fast - slow ? maxlen : fast - slow;
                    slow = fast - 1;
                } else {
                    count++;
                }
            } else {
                count = 1;
            }
            fast++;
        }
        
        maxlen = maxlen > fast - slow ? maxlen : fast - slow;
        
        return maxlen;
    }
};


class Solution {
public:
    /**
     * @param s: the string
     * @return: length of longest semi alternating substring
     */
    int longestSemiAlternatingSubstring(string &s) {
        // write your code here
        int sublen;
        int count;
        int maxlen = 0;
        int size = s.size();

        if (size < 3) {
            return size;
        }

        sublen = count = 1;
        for (int i = 1; i < size; i++) {
            if (s[i - 1] == s[i]) {
                if (count == 2) {
                    maxlen = maxlen > sublen ? maxlen : sublen;
                    sublen = 1;
                } else {
                    count++;
                }
            } else {
                count = 1;
            }
            sublen++;
        }

	return maxlen > sublen ? maxlen : sublen;
    }
};
